package com.example.demo.recursive.tasks;

import com.example.demo.dao.IOrderDao;
import com.example.demo.model.Order;

import java.util.List;
import java.util.concurrent.RecursiveTask;

public class InsertOrderTask extends RecursiveTask<Integer> {
    private static final long DIVIDING_LINE = 100;
    int low;
    int high;
    List<Order> orders;
    IOrderDao orderDao;

    public InsertOrderTask(int low, int high, List<Order> orders, IOrderDao orderDao) {
        this.low = low;
        this.high = high;
        this.orders = orders;
        this.orderDao = orderDao;
    }


    @Override
    protected Integer compute() {
        if (high - low > DIVIDING_LINE) {
            Integer success = 0;
            List<Order> subList = this.orders.subList(low, high);
            for (Order order : subList) {
                success += orderDao.insertOrder(order);
            }
            return success;
        } else {
            //继续拆分
            int middle = high / 2;
            InsertOrderTask left = new InsertOrderTask(low, middle, orders, orderDao);
            InsertOrderTask right = new InsertOrderTask(low, middle, orders, orderDao);
            left.fork();
            right.fork();
            return left.join() + right.join();
        }
    }
}
